package com.fangdd.logtrace;

import java.util.regex.Pattern;

/**
 * Created by sulong on 16-9-2.
 */
public class TraceId {
    private static Pattern pattern = Pattern.compile("([0-9a-zA-Z_-]{1,36}(#[0-9]+)*)(:[0-9]+(#[0-9]+)*)*");

    private String root;
    private String traceIdStr;

    public TraceId(String traceIdStr) {
        if (traceIdStr == null || traceIdStr.length() == 0) {
            throw new IllegalArgumentException(" tractId string is empty ");
        }

        if (!pattern.matcher(traceIdStr).matches()) {
            throw new IllegalArgumentException(" bad format :" + traceIdStr);
        }

        this.traceIdStr = traceIdStr;

        String[] segments = traceIdStr.split(":");
        this.root = segments[0].split("#")[0];
    }

    public String getRoot() {
        return this.root;
    }

    public boolean isUnset() {
        return "_unset".equals(root);
    }

    public static final TraceId UNSET = new TraceId("_unset");

    @Override
    public String toString() {
        return this.traceIdStr;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TraceId traceId = (TraceId) o;

        return traceIdStr.equals(traceId.traceIdStr);

    }

    @Override
    public int hashCode() {
        return traceIdStr.hashCode();
    }
}
